import axios from "axios";
import {getRedirectUrl} from '@/tools'
const request = axios.create({
  baseURL: import.meta.env.VITE_SERVER_ADDRESS,
  timeout: 5000,
});

request.interceptors.request.use(
  (config: any) => {
    return {
      ...config,
      headers: {
        Authorization: `Bearer ${localStorage.getItem("token")}`,
      },
    };
  },
  (error) => {
    return Promise.reject(error);
  }
);

request.interceptors.response.use(
  function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    if (response.status === 200) {
      return response.data;
    }

    return response;
  },
  function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    console.log("reqeust err:", error);
    if (error.response.status === 401 && window.location.search.indexOf("code") === -1) {
      localStorage.removeItem('token');
      window.location.href = getRedirectUrl();
    }
    if (error.response.status === 500) {
      alert(error.response.data.msg);
    }
    return Promise.reject(error);
  }
);

export default request;
